#include <stdio.h>
#include <properties.h>
#include <string.h>

#define ERROR(format, args...) fprintf(stderr, format "\n", ##args)

int length_check(const char *key, const char *value) {
    if (key == NULL) {
        ERROR("key is NULL");
        return -1;
    }
    int keylen = strlen(key);
    if (keylen <= 0 || keylen >= PROP_NAME_MAX) {
        ERROR("invalid key length %d, valid range is 0 < keylen < %d: %s", keylen, PROP_NAME_MAX, key);
        return -1;
    }
    int valuelen = strlen(value);
    if (valuelen >= PROP_VALUE_MAX) {
        ERROR("invalid value length %d, valid range is 0 < length < %d: %s", valuelen, PROP_VALUE_MAX, value);
        return -1;
    }
    return 0;
}

int main(int argc, char *argv[]) {
    if (argc < 2) {
        ERROR("usage: setprop <key> <value>");
        return 1;
    }
    const char *key = argv[1];
    const char *value = argc == 2 ? "" : argv[2];
    if (length_check(key, value) != 0) return 1;

    if (property_set(key, value)) {
        ERROR("could not set property");
        return 1;
    }

    return 0;
}
